package cn.fl.warrant.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcBscInfoService;
import cn.fl.warrant.service.IArcReceiptMainService;
import cn.fl.warrant.transform.ArcReceiptDetailVOTransform;
import cn.fl.warrant.vo.ArcBscInfoVO;
import cn.fl.warrant.vo.ArcReceiptDetailVO;
import cn.fl.warrant.vo.ArcReceiptMainVO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import fl.ref.fribaseinfo.service.IFriBaseInfoApiService;
import fl.warrant.facade.archive.condition.ArcReceiptConditionRQueryCondition;
import fl.warrant.facade.archive.condition.ArcReceiptDetailQueryCondition;
import fl.warrant.facade.archive.condition.ArcReceiptMainQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcReceiptConditionRDTO;
import fl.warrant.facade.archive.dto.ArcReceiptMainDTO;

/**
 * @Description: 交接单主表 控制层
 */
@Controller
@RequestMapping("/archive/arcReceiptMain")
public class ArcReceiptMainController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcReceiptMainController.class);
	
	
	@Autowired
	private IArcReceiptMainService arcReceiptMainService;//交接单
	@Autowired
	private ICstBscInfoService cstBscInfoService;//客户
	@Autowired
	private IArcBscInfoService arcBscInfoService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	@Autowired
	private IFriBaseInfoApiService friBaseInfoApiService;
	
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping("/toListPage.do")
	public String toListPage(HttpServletRequest request) {
		this.setAttribute(request);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return "archive/arcReceiptMain/arcReceiptMainList";
	}

	/**
	 * 列表页面初始化
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/initList.do")
	@ResponseBody
	public Object initList(ArcReceiptMainQueryCondition qc,HttpServletRequest request) {
		BaseLogUtils.info(logger, "initList", "列表页面初始化-进入", CurrentThreadContext.getCurrentUserName());
		try {
			String currentPage = request.getParameter("page");
			String pageSize = request.getParameter("pagesize");
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}
			if (StringUtils.isNotEmpty(pageSize)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

//		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
//		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
			qc.setCurrentVersion(ArchiveConstants.CURRENT_VERSION_YES);
			page.setCondition(qc);
			Pager pager = this.arcReceiptMainService.searchListPage(page);
			List<ArcReceiptMainVO> list = (List<ArcReceiptMainVO>) pager.getResultList();
			BaseLogUtils.info(logger, "initList", "列表页面初始化List<ArcReceiptMainVO> list ="+list, CurrentThreadContext.getCurrentUserName());
			return new ListPageVO<ArcReceiptMainVO>(list, pager.getTotalCount());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "列表页面初始化-错误:"+e.getMessage(),e);
			e.printStackTrace();
			throw e;
		}
	}

	
	/**
	 * 跳转到保存页面(新增和修改)
	 */
	@RequestMapping(value = "/toSave.do")
	public Object toSave(ArcReceiptMainVO entity ,HttpServletRequest request) {
		this.setAttribute(request);//筛选条件查询
		
		if(entity.getId() == null) {//新增
			entity.setVersion(1L);
		}else {//修改
			entity = arcReceiptMainService.selectById(entity.getId());//查询交接单主表
			if(entity != null) {
				setReceiptR(request,entity);//设置交接单筛选条件
			}
		}
		
		request.setAttribute("entity", entity);
		request.setAttribute("operate", request.getParameter("operate"));
		return "archive/arcReceiptMain/arcReceiptMainSave";
	}
	
	private void setAttribute(HttpServletRequest request) {
		request.setAttribute("lesseeTypeList", arcReceiptMainService.getKvList(DictionaryConstant.CODE_GRP_CST_TYP_CD));//承租人类型(客户类型)
		request.setAttribute("contractSignList", arcReceiptMainService.getKvList(DictionaryConstant.CODE_CNT_TYP_CD));//合同签署方式
//		request.setAttribute("buOrgCdList", arcReceiptMainService.getKvDescList(DictionaryConstant.CODE_SYS_BU_ORG_CD));//事业部
		request.setAttribute("buOrgCdList", cstBscInfoService.searchBusinessOrgList());//事业部
		request.setAttribute("prjBizTypeList", arcReceiptMainService.getKvList(DictionaryConstant.CODE_PRJ_BIZ_TYP_CD));//业务类型
		request.setAttribute("settleTypeList", this.filterSettleTypeList(arcReceiptMainService.getKvList(DictionaryConstant.CODE_PRJ_PRD_STS_CD)));//结清类型（支付表状态）
		request.setAttribute("guaranteeList", arcReceiptMainService.getKvList(ArchiveConstants.ARC_GUARANTEE));//担保人
		request.setAttribute("guaranteeTypeList", arcReceiptMainService.getKvList(ArchiveConstants.ARC_GUARANTEE_TYPE));//担保人类型
		request.setAttribute("guaranteeSignList", arcReceiptMainService.getKvList(DictionaryConstant.CODE_CNT_TYP_CD));//担保签署方式(与合同签署方式同一个字典)
		request.setAttribute("assetManageList", arcReceiptMainService.getKvList(ArchiveConstants.ARC_ASSET_MANAGE));//资管业务
		
		//所有项目类型
		List<KeyValueVO> projectTypeList = this.prjBscInfoService.getPrjTypCdALLKV();
		if(CollectionUtils.isNotEmpty(projectTypeList)) {
			for (KeyValueVO keyValueVO : projectTypeList) {
				keyValueVO.setIsHide(false);
			}
			request.setAttribute("projectTypeList",projectTypeList);
		}
		
//        String operate = request.getParameter("operate");
//        //	REQ-3675  历史项目类型清洗 详情使用所有 新增修改使用清洗后的
//        if (Objects.equals(operate, "view")) {
//            request.setAttribute("projectTypeList", this.prjBscInfoService.getPrjTypCdALLKV());//项目类型
//        } else {
//            request.setAttribute("projectTypeList", this.prjBscInfoService.getProjectTypeList());//项目类型
//        }

		FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
		condition.setInsUseCd("2");//只查询资管类型的融资机构
		List<FriBaseInfoDTO> friBaseInfoDTOList = friBaseInfoApiService.searchList(condition);
		request.setAttribute("friBaseInfoDTOList",friBaseInfoDTOList);//融资机构(资管)
	}

	//过滤结清类型，只需要部分值
	private List<KeyValueVO> filterSettleTypeList(List<KeyValueVO> keyValueVOList) {
		
		List<KeyValueVO> newKeyValueVOList = new ArrayList<KeyValueVO>();
		if(keyValueVOList != null && keyValueVOList.size() >0) {
			for (KeyValueVO keyValueVO : keyValueVOList) {
				if("S010301".equals(keyValueVO.getKey())//已正常结清
						|| "S010401".equals(keyValueVO.getKey())//已提前结清
						|| "S010501".equals(keyValueVO.getKey())//已强制结清
						|| "S0106020101".equals(keyValueVO.getKey())//拖回已处置
						|| "S01060203010101".equals(keyValueVO.getKey())//优车已处置
						|| "S0106020201".equals(keyValueVO.getKey())//已赎回结清
						) {
					newKeyValueVOList.add(keyValueVO);
				}
			}
		}
		
		return newKeyValueVOList;
	}
	//设置交接单筛选条件
	private void setReceiptR(HttpServletRequest request, ArcReceiptMainVO entity) {
		//查询交接单筛选条件
		ArcReceiptConditionRQueryCondition condition = new ArcReceiptConditionRQueryCondition();
		condition.setArcReceiptMainId(entity.getId());
		List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
		if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
			setEachReceiptR(arcReceiptConditionRDTOList,DictionaryConstant.CODE_GRP_CST_TYP_CD, "lesseeTypeList", request);//承租人类型(客户类型)
			setEachReceiptR(arcReceiptConditionRDTOList,DictionaryConstant.CODE_CNT_TYP_CD, "contractSignList", request);//合同签署方式
			setEachReceiptR(arcReceiptConditionRDTOList,DictionaryConstant.CODE_SYS_BU_ORG_CD, "buOrgCdList", request);//事业部
			setEachReceiptR(arcReceiptConditionRDTOList,DictionaryConstant.CODE_PRJ_BIZ_TYP_CD, "prjBizTypeList", request);//业务类型
			setEachReceiptR(arcReceiptConditionRDTOList,DictionaryConstant.CODE_PRJ_PRD_STS_CD, "settleTypeList", request);//结清类型（支付表状态）
			setEachReceiptR(arcReceiptConditionRDTOList,ArchiveConstants.ARC_GUARANTEE, "guaranteeList", request);//担保人
			setEachReceiptR(arcReceiptConditionRDTOList,ArchiveConstants.ARC_GUARANTEE_TYPE, "guaranteeTypeList", request);//担保人类型
			setEachReceiptR(arcReceiptConditionRDTOList,ArchiveConstants.ARC_GUARANTEE_SIGN, "guaranteeSignList", request);//担保签署方式
			setEachReceiptR(arcReceiptConditionRDTOList,ArchiveConstants.ARC_CODE_PRJ_TYPE_CD, "projectTypeList", request);//项目类型
			setEachReceiptRForFundCompany(arcReceiptConditionRDTOList, request);//金融机构
			setEachReceiptR(arcReceiptConditionRDTOList,ArchiveConstants.ARC_ASSET_MANAGE, "assetManageList", request);//资管业务
		}
	}
	
	//设置筛选条件：金融机构 checked选项
	private void setEachReceiptRForFundCompany(List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList,HttpServletRequest request) {
		List<FriBaseInfoDTO> friBaseInfoDTOList = (List<FriBaseInfoDTO>)request.getAttribute("friBaseInfoDTOList");
		if(friBaseInfoDTOList != null && friBaseInfoDTOList.size() >0) {
			for (FriBaseInfoDTO friBaseInfoDTO : friBaseInfoDTOList) {
				for (ArcReceiptConditionRDTO arcReceiptConditionRDTO : arcReceiptConditionRDTOList) {
					if(friBaseInfoDTO.getId() != null && friBaseInfoDTO.getId().toString().equals(arcReceiptConditionRDTO.getCode())) {
						friBaseInfoDTO.setRem("checked");
						break;
					}
				}
			}
		}
	}

	//设置交接单每一条的筛选条件
	@SuppressWarnings("unchecked")
	private void setEachReceiptR(List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList,String codeGrpCd,String attName,HttpServletRequest request) {
		List<KeyValueVO>  keyValueVOList = (List<KeyValueVO>)request.getAttribute(attName);
		for (ArcReceiptConditionRDTO arcReceiptConditionRDTO : arcReceiptConditionRDTOList) {
			if(codeGrpCd.equals(arcReceiptConditionRDTO.getCodeGrpCd())) {
				if(keyValueVOList != null) {
					for (KeyValueVO keyValueVO : keyValueVOList) {
							if(keyValueVO.getKey().equals(arcReceiptConditionRDTO.getCode())) {
								keyValueVO.setIsHide(true);
							}
					}
				}
			}
		}
	}

	/**
	 * 新增和修改
	 */
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public Object save(ArcReceiptMainVO entity,String json,HttpServletRequest request){
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			List<ArcReceiptDetailVO> arcReceiptDetailVOList = JSON.parseArray(json, ArcReceiptDetailVO.class);
			entity.setArcReceiptDetailVOList(arcReceiptDetailVOList);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			
			//必要验证
			if (StringUtils.isBlank(entity.getLesseeType()) && StringUtils.isBlank(entity.getContractSign()) && StringUtils.isBlank(entity.getBuOrgCd())
					&& StringUtils.isBlank(entity.getPrjBizType())&& StringUtils.isBlank(entity.getGuarantee())&& StringUtils.isBlank(entity.getSettleType())
					&& StringUtils.isBlank(entity.getGuaranteeSign())
					&& StringUtils.isBlank(entity.getProjectType()) && StringUtils.isBlank(entity.getFundCompany())
					&& StringUtils.isBlank(entity.getAssetManage())) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("至少选择一条筛选条件");
				return result;
			}
		
			
			if(entity.getId() == null) {//新增
				
				//验证权证名称不能重复
				ArcReceiptMainQueryCondition qc = new ArcReceiptMainQueryCondition();
				qc.setListName(entity.getListName());
				List<ArcReceiptMainDTO> list = arcReceiptMainService.searchList(qc);
				if(list != null && list.size() >0) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("交接单名称已存在");
					return result;
				}
				
				//验证筛选条件
				ArcReceiptMainVO arcReceiptMainVO = this.checkArcReceiptR(entity);
				if(arcReceiptMainVO != null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("与交接单 "+arcReceiptMainVO.getListName()+" 的筛选条件重复");
					return result;
				}
				
				String uuid = UUID.randomUUID().toString().replace("-", "");
				entity.setReceiptNo(uuid);//交接单编号
				entity.setVersion(1L);//当前版本号
				Long id = this.arcReceiptMainService.add(entity);
				result.setData(id);
			}else {//修改
				
				ArcReceiptMainVO arcReceiptMainVO = arcReceiptMainService.selectById(entity.getId());
				if(arcReceiptMainVO != null) {
					
					//验证筛选条件
					ArcReceiptMainVO arcReceiptMainVOHave = this.checkArcReceiptR(entity);
					if(arcReceiptMainVOHave != null) {
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("与交接单 "+arcReceiptMainVOHave.getListName()+" 的筛选条件重复");
						return result;
					}
					
//					entity.setListName(entity.getListName());//交接单名称
					entity.setVersion(arcReceiptMainService.getMaxVersion(arcReceiptMainVO.getReceiptNo())+1);//当前版本号+1
					entity.setReceiptNo(arcReceiptMainVO.getReceiptNo());//编码
					
					if(this.arcReceiptMainService.updateArcReceiptMain(entity)) {
						result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
					}
				}
			}
			BaseLogUtils.info(logger, "save", "操作数据. DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "save", "操作数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName(),ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "save", "操作数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName(),ex);
		}
		return result;
	}
	
	private ArcReceiptMainVO checkArcReceiptR(ArcReceiptMainVO vo) {
		
		ArcReceiptMainQueryCondition qc = new ArcReceiptMainQueryCondition();
		
		if (StringUtils.isNotBlank(vo.getLesseeType())) {//承租人类型
			qc.setLesseeType(replaceChar(vo.getLesseeType()));
		}
		if (StringUtils.isNotBlank(vo.getContractSign())) {//合同签署方式
			qc.setContractSign(replaceChar(vo.getContractSign()));
		}
		if (StringUtils.isNotBlank(vo.getBuOrgCd())) {//事业部
			qc.setBuOrgCd(replaceChar(vo.getBuOrgCd()));
		}
		if (StringUtils.isNotBlank(vo.getPrjBizType())) {//业务类型
			qc.setPrjBizType(replaceChar(vo.getPrjBizType()));
		}
		if (StringUtils.isNotBlank(vo.getGuarantee())) {//担保人
			qc.setGuarantee(replaceChar(vo.getGuarantee()));
		}
		if (StringUtils.isNotBlank(vo.getGuaranteeType())) {//担保人类型
			qc.setGuaranteeType(replaceChar(vo.getGuaranteeType()));
		}
		if (StringUtils.isNotBlank(vo.getSettleType())) {//结清类型
			qc.setSettleType(replaceChar(vo.getSettleType()));
		}
		if (StringUtils.isNotBlank(vo.getProjectType())) {//项目类型
			qc.setProjectType(replaceChar(vo.getProjectType()));
		}
		if (StringUtils.isNotBlank(vo.getFundCompany())) {//融资机构
			qc.setFundCompany(replaceChar(vo.getFundCompany()));
		}
		if (StringUtils.isNotBlank(vo.getAssetManage())) {//融资机构
			qc.setAssetManage(replaceChar(vo.getAssetManage()));
		}
		
		List<ArcReceiptMainVO> arcReceiptMainRepeat = new ArrayList<ArcReceiptMainVO>();//重复的交接单
		List<ArcReceiptMainVO> arcReceiptMainVOList = (List<ArcReceiptMainVO>) this.arcReceiptMainService.checkArcReceiptR(qc);
		if(arcReceiptMainVOList != null && arcReceiptMainVOList.size() >0) {
			//1 排除没选大类的筛选条件
			//1.1查询交接单筛选条件
			for (ArcReceiptMainVO arcReceiptMainVO : arcReceiptMainVOList) {
				boolean addFlag = true;//能否添加标识，true为添加重复的交接单
				
				ArcReceiptConditionRQueryCondition condition = new ArcReceiptConditionRQueryCondition();
				condition.setArcReceiptMainId(arcReceiptMainVO.getId());
				
			  if (StringUtils.isBlank(vo.getLesseeType())) {//如果没勾选大类：项目类型，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_CODE_PRJ_TYPE_CD);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
				
			  if (StringUtils.isBlank(vo.getBuOrgCd())) {//如果没勾选大类：事业部，则去掉已勾选的交接单
					condition.setCodeGrpCd(DictionaryConstant.CODE_SYS_BU_ORG_CD);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
			  
			  if (StringUtils.isBlank(vo.getPrjBizType())) {//如果没勾选大类：业务类型，则去掉已勾选的交接单
					condition.setCodeGrpCd(DictionaryConstant.CODE_PRJ_BIZ_TYP_CD);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
			  
			  if (StringUtils.isBlank(vo.getSettleType())) {//如果没勾选大类：结清类型，则去掉已勾选的交接单
					condition.setCodeGrpCd(DictionaryConstant.CODE_PRJ_PRD_STS_CD);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
			  
			  if (StringUtils.isBlank(vo.getGuarantee())) {//如果没勾选大类：担保人，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_GUARANTEE);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
			  
			  if (StringUtils.isBlank(vo.getGuaranteeType())) {//如果没勾选大类：担保人类型，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_GUARANTEE_TYPE);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
			  
				if (StringUtils.isBlank(vo.getProjectType())) {//如果没勾选大类：项目类型，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_CODE_PRJ_TYPE_CD);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
				
				if (StringUtils.isBlank(vo.getFundCompany())) {//如果没勾选大类：金融机构，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_FUND_COMPANY);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
				
				if (StringUtils.isBlank(vo.getAssetManage())) {//如果没勾选大类：资管业务，则去掉已勾选的交接单
					condition.setCodeGrpCd(ArchiveConstants.ARC_ASSET_MANAGE);
					List<ArcReceiptConditionRDTO> arcReceiptConditionRDTOList =  arcReceiptMainService.searchArcReceiptConditionRList(condition);
					if(arcReceiptConditionRDTOList != null && arcReceiptConditionRDTOList.size() >0) {
						addFlag = false;//不添加，认为不重复
					}
				}
				
				if(addFlag) {
					arcReceiptMainRepeat.add(arcReceiptMainVO);
				}
			}
			
			
			if(arcReceiptMainRepeat.size() >0) {
				if(vo.getId() == null) {//新增验证
					return arcReceiptMainRepeat.get(0);
				}else {//修改验证，排除自身
					for (ArcReceiptMainVO arcReceiptMainVO : arcReceiptMainRepeat) {
						if(!vo.getId().equals(arcReceiptMainVO.getId())) {
							return arcReceiptMainVO;
						}
					}
				}
			}
		}
		
		return null;
	}
	
	
	/**
	 * 分号替换为逗号
	 * @param obj
	 * @return
	 */
	private String replaceChar(String obj) {
		if(StringUtils.isBlank(obj)) {
			return obj;
		}
//		return obj.replaceAll(";",",");
		return obj;
	}
	
	/**
	 * 逻辑删除
	 */
	@RequestMapping(value = "/removeById.do")
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcReceiptMainService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	
	/**
	 * 历史版本
	 */
	@RequestMapping("/historicalVersion.do")
	public Object historicalVersion(HttpServletRequest request) {
	
		request.setAttribute("id", request.getParameter("id"));
		return "archive/arcReceiptMain/historicalVersion";
	}
	
	/**
	 * 历史版本查询
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/historicalVersionPage.do")
	@ResponseBody
	public Object historicalVersionPage(ArcReceiptMainQueryCondition qc,HttpServletRequest request) {
		
		Long id ;
			try {
				id = Long.valueOf(qc.getId());
			} catch (NumberFormatException e) {
				e.printStackTrace();
				BaseLogUtils.error(logger, "historicalVersionPage", "转换id为Long类型出错.[id="+qc.getId()+"]"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
				return null;
			}
		ArcReceiptMainVO arcReceiptMainVO = arcReceiptMainService.selectById(id);
		if(arcReceiptMainVO == null) {
			BaseLogUtils.error(logger, "historicalVersionPage", "arcReceiptMainService.selectById(id)数据不存在.[id="+qc.getId()+"]", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		qc.setReceiptNo(arcReceiptMainVO.getReceiptNo());
		page.setCondition(qc);
		Pager pager = this.arcReceiptMainService.searchListPage(page);
		return new ListPageVO<ArcReceiptMainVO>((List<ArcReceiptMainVO>) pager.getResultList(), pager.getTotalCount());
	}
	
	
	/**
	 * 设置历史版本
	 */
	@RequestMapping(value = "/setHistoricalVersion.do")
	@ResponseBody
	public Object setHistoricalVersion(ArcReceiptMainVO entity,HttpServletRequest request){
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
				ArcReceiptMainVO arcReceiptMainVO = arcReceiptMainService.selectById(entity.getId());
				if(arcReceiptMainVO != null) {
					
					//1、设置其他版本不启用
					arcReceiptMainVO.setCurrentVersion(ArchiveConstants.CURRENT_VERSION_NO);
					this.arcReceiptMainService.updateCurrentVersion(arcReceiptMainVO);
					//2、设置当前版本启用
					entity.setCurrentVersion(ArchiveConstants.CURRENT_VERSION_YES);
					this.arcReceiptMainService.update(entity);
					
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
				}
			BaseLogUtils.info(logger, "setHistoricalVersion", "操作数据. DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "setHistoricalVersion", "操作数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName(),ex);
		}
		return result;
	}
	
	
	/**
	 * 查询交接单明细(不分页)
	 */
	@RequestMapping("/arcReceiptDetailList.do")
	@ResponseBody
	public Object arcReceiptDetailList(ArcReceiptDetailQueryCondition qc) {

		if(qc.getArcReceiptMainId() == null) return null;
		
		List<ArcReceiptDetailVO> arcReceiptDetailVOList = ArcReceiptDetailVOTransform.toVOList(this.arcReceiptMainService.arcReceiptDetailList(qc));
		for(int i=0;i<arcReceiptDetailVOList.size();i++) {
			ArcReceiptDetailVO arcReceiptDetailVO = arcReceiptDetailVOList.get(i);
			ArcBscInfoVO arcBscInfoVO = arcBscInfoService.selectById(arcReceiptDetailVO.getArcBscInfo());
			if(arcBscInfoVO != null) {
				arcReceiptDetailVO.setWarrantName(arcBscInfoVO.getWarrantName());
				arcReceiptDetailVO.setWarrantTypeNm(arcBscInfoVO.getWarrantTypeNm());
//				SysDictionaryDTO dictionary  = sysDictionaryApiService.getCode(ArchiveConstants.SYS_CODE, ArchiveConstants.ORG_CODE,
//						ArchiveConstants.ARC001, arcBscInfoVO.getWarrantType());
//				if(dictionary != null){
//					arcReceiptDetailVO.setWarrantType(dictionary.getCodeNm());
//				}
			}
		}
		
		return new ListPageVO<ArcReceiptDetailVO>(arcReceiptDetailVOList, arcReceiptDetailVOList.size());
	}
	
	/**
	 *  结清类型（下拉复选框）  
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/settleTypeList.do")
	@ResponseBody
	public List<KeyValueVO> settleTypeList() {
		
		return this.filterSettleTypeList(arcReceiptMainService.getKvList(DictionaryConstant.CODE_PRJ_PRD_STS_CD));//结清类型（支付表状态）
	}
}

